package com.xps.and.yuntong.Ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.xps.and.yuntong.Constants;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.DensityUtil;
import com.xps.and.yuntong.aly.OssService;
import com.xps.and.yuntong.aly.STSGetter;
import com.xps.and.yuntong.aly.UIDisplayer;
import com.xps.and.yuntong.base.BaseActivity;
import com.jude.utils.JUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * Created by administrator on 2017-12-12.
 */

public class PersonalZiliaoActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_fanhui, iv_right, iv_cheliang_choose, iv_ziliao_touxiang;
    private TextView tv_middle, tv_ziliao_name, tv_ziliao_sex, tv_ziliao_age, tv_ziliao_shenfenzheng, tv_ziliao_yue;
    private RelativeLayout rl_cheliang_choose;
    private LinearLayout ll_name, ll_sex;

    private static final int RESULT_LOAD_IMAGE = 1;
    int successPicCount = 0;//已经成功的个数
    int actualPicCount = 0;//应该成功的个数
    private UIDisplayer displayer;
    private OssService ossService;
    private String picturePath = "";
    String User_Phone = "";
    String headImg = "";

    //修改姓名性别
    private String SJ_name;
    private String CheckBoxString;

    @Override
    protected int getLayout() {
        return R.layout.activity_person_ziliao;
    }

    @Override
    protected void setData() {
        ziliaoxianshi();
    }

    @Override
    protected void init(Bundle inBundle) {

        initView();
        displayer = new UIDisplayer(this);
        ossService = initOSS(Constants.endpoint, displayer);


    }

    @Override
    public void photoUploadSuccess() {
        successPicCount++;
        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount + "photoUploadSuccess");
//        modifyme();
        dissmisDialog();

    }

    private void initView() {

        iv_fanhui = (ImageView) findViewById(R.id.iv_fanhui);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.GONE);
        iv_cheliang_choose = (ImageView) findViewById(R.id.iv_cheliang_choose);
        iv_ziliao_touxiang = (ImageView) findViewById(R.id.iv_ziliao_touxiang);

        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_middle.setText(R.string.personl_info);
        tv_ziliao_name = (TextView) findViewById(R.id.tv_ziliao_name);
        tv_ziliao_sex = (TextView) findViewById(R.id.tv_ziliao_sex);
        tv_ziliao_shenfenzheng = (TextView) findViewById(R.id.tv_ziliao_shenfenzheng);
        tv_ziliao_yue = (TextView) findViewById(R.id.tv_ziliao_yue);


        iv_fanhui.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_fanhui:

                finish();
                break;
            case R.id.iv_ziliao_touxiang:
//                selectDialog();

                break;
            case R.id.ll_name:
//                showCustomizeDialog();

                break;
            case R.id.ll_sex:
//                XBDialog();
                break;

            case R.id.rl_cheliang_choose:
//                Intent intent=new Intent(PersonalZiliaoActivity.this,PersonalCheliangZiliaoActivity.class);
//                startActivity(intent);
//                finish();

                break;

        }

    }

    void selectDialog() {
        final Dialog bottomDialog = new Dialog(PersonalZiliaoActivity.this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(PersonalZiliaoActivity.this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(PersonalZiliaoActivity.this, 16f);
        params.bottomMargin = DensityUtil.dp2px(PersonalZiliaoActivity.this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        TextView XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                bottomDialog.dismiss();
            }
        });
        TextView XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setVisibility(View.GONE);
        TextView cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            Log.d("PickPicture", picturePath);
            cursor.close();
            Glide.with(PersonalZiliaoActivity.this).load(picturePath)
                    .bitmapTransform(new CropCircleTransformation(PersonalZiliaoActivity.this))
                    .into(iv_ziliao_touxiang);
            displayer.displayInfo("文件: " + picturePath + "\n大小: " + String.valueOf(picturePath.length()));
            startUpload();
        }
    }

    //上传图片
    void startUpload() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String objectName = "headImg/" + formatter.format(curDate) + "/" + User_Phone + ".png";
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("headImg", "http://uu-driver.oss-cn-beijing.aliyuncs.com/" + objectName);
        spEd.commit();
        ossService.asyncPutImage(objectName, picturePath, User_Phone);
//        showDialogNoCancel();
        actualPicCount++;
    }

    public OssService initOSS(String endpoint, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类

        if (Constants.stsServer.equals("")) {
            credentialProvider = new STSGetter();
        } else {
            credentialProvider = new STSGetter(Constants.stsServer);
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        return new OssService(oss, Constants.bucket, displayer);
    }

    private void ziliaoxianshi() {


        if (JUtils.getSharedPreference().getString("head_img", "") != null) {
            Glide.with(PersonalZiliaoActivity.this).load(JUtils.getSharedPreference().getString("head_img", ""))
                    .placeholder(R.drawable.logo)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .bitmapTransform(new CropCircleTransformation(PersonalZiliaoActivity.this))
                    .into(iv_ziliao_touxiang);
        }
        if (JUtils.getSharedPreference().getString("name", "") != null) {
            tv_ziliao_name.setText(JUtils.getSharedPreference().getString("name", ""));
        }
        if ((JUtils.getSharedPreference().getInt("sex", -1) + "") != null) {
            if (JUtils.getSharedPreference().getInt("sex", -1) == 1) {
                tv_ziliao_sex.setText("男");

            } else if (JUtils.getSharedPreference().getInt("sex", -1) == 2) {
                tv_ziliao_sex.setText("女");
            }
        }
        if (JUtils.getSharedPreference().getString("balance", "") != null) {
            tv_ziliao_yue.setText(JUtils.getSharedPreference().getString("balance", ""));
        }


    }
}
